<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>作</title>
    <link rel="stylesheet" href="./index.css">
</head>

<body>
    <div class="wrap">
        <div class="title">学生系统</div>
        <div id="form">
            <p>姓名<input id="username" type="text" value="" /></p>
            <p>年龄<input id="age" type="text" value="" /></p>
            <p>性别
                <select id="gender">
                    <option>你猜</option>
                    <option>女</option>
                    <option>男</option>
                </select>
            </p>
            <p>
                <input type="button" value="添加" id="addBtn" />
                <input type="button" value="排序" id="sortBtn" />
            </p>
        </div>
        <table id="table">
            <thead>
                <tr>
                    <th>姓名</th>
                    <th>年龄</th>
                    <th>性别</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>

            </tbody>
        </table>
    </div>
    <script>
        var arr = [];
        var tbodyEle = document.querySelector("tbody");
        function renderDom(arr){
            tbodyEle.innerHTML = "";
            arr.forEach(function(item){
                var trEle = document.createElement("tr");
                trEle.innerHTML = "<td>"+item.username+"</td><td>"+item.age+"</td><td>"+item.gender+"</td><td class='del'>删除</td>";
                tbodyEle.appendChild(trEle);
            })
             var delEles = document.querySelectorAll(".del");
            delEles.forEach(function(delEle,key){
                delEle.onclick = function(){
                    arr.splice(key,1);
                    renderDom(arr);
                }
            })
        } 
        var usernameELe =  document.querySelector("#username");
        var ageEle = document.querySelector("#age");
        var genderEle = document.querySelector("#gender");
        
        document.querySelector("#addBtn").onclick = function(){
            var username = usernameELe.value;
            var age = ageEle.value;
            var gender = genderEle.value;
            arr.push({
                username:username,
                age:age,
                gender:gender
            })
            console.log(arr);
            renderDom(arr);
        }
    
    
    
        // 排序操作 
    
        var sortBtn = document.querySelector("#sortBtn");
        sortBtn.onclick = function(){
    
            arr.sort(function(a,b){
                return a.age-b.age;
            });
            renderDom(arr);
        }
    
        </script>
</body>

</html>